package com.example.project.controller.project;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.project.annotation.Log;
import com.example.project.core.controller.BaseController;
import com.example.project.core.domain.AjaxResult;
import com.example.project.entity.Issue;
import com.example.project.entity.IssueRelation;
import com.example.project.enums.BusinessType;
import com.example.project.service.IssueRelationService;
import com.example.project.service.IssueService;
import com.example.project.service.JournalService;
import com.example.project.utils.StringUtils;

/**
 * 关联Controller
 * 
 * @author ruoyi
 * @date 2025-09-19
 */
@Controller
@RequestMapping("/issue/relation")
public class IssueRelationController extends BaseController {

	private String prefix = "pm/issue";

	@Autowired
	private IssueService issueService;

	@Autowired
	private JournalService journalService;

	@Autowired
	private IssueRelationService issueRelationService;

	/**
	 * 获取问题的关联问题列表
	 */
	@GetMapping("/list/{id}")
	@ResponseBody
	public AjaxResult getRelations(@PathVariable("id") Long issueId) {
		List<IssueRelation> relations = issueRelationService.selectIssueRelationsByIssueId(issueId);
		if (relations != null && !relations.isEmpty()) {
			// 完善关联问题信息
			for (IssueRelation relation : relations) {
				// 根据关联关系类型确定需要显示的问题信息
				if (issueId.equals(relation.getIssueFromId())) {
					// 当前问题是源问题，显示目标问题
					Issue relatedIssue = issueService.selectIssuesById(relation.getIssueToId());
					if (relatedIssue != null) {
						relation.setIssueTo(relatedIssue);
					}
				} else if (issueId.equals(relation.getIssueToId())) {
					// 当前问题是目标问题，显示源问题
					Issue relatedIssue = issueService.selectIssuesById(relation.getIssueFromId());
					if (relatedIssue != null) {
						relation.setIssueFrom(relatedIssue);
					}
				}
			}
		}
		return AjaxResult.success(relations);
	}

	/**
	 * 添加问题关联
	 */
	@Log(title = "关联相关需求", businessType = BusinessType.INSERT)
	@PostMapping("/add/{id}")
	@ResponseBody
	public AjaxResult addRelation(@PathVariable("id") Long issueId, @RequestParam("issueToId") String issueToId,
			@RequestParam("relationType") String relationType,
			@RequestParam(value = "description", required = false) String description) {
		List<Map<String, String>> list = Lists.newArrayList();
		Map<String, String> map = new HashMap<String, String>();
		String[] split = issueToId.split(",");
		for (String string : split) {
			if (StringUtils.isNotBlank(string)) {
				int result = issueRelationService.addIssueRelation(issueId, Long.parseLong(string.trim()), relationType,
						description, getLoginName());
				if (result > 0) {
					issueRelationService.addIssueRelation(Long.parseLong(string.trim()), issueId, relationType,
							description, getLoginName());
				}
				map.put("id", "#" + string.trim());
				map.put("result", String.valueOf(result));
				list.add(map);
			}
		}
		return success(list);
	}

	/**
	 * 删除问题关联
	 */
	@Log(title = "取消需求关联", businessType = BusinessType.DELETE)
	@PostMapping("/remove/{id}")
	@ResponseBody
	public AjaxResult removeRelation(@PathVariable("id") Long relationId) {
		// 先查询要删除的关联关系，用于创建历史记录
		IssueRelation issueRelation = issueRelationService.selectIssueRelationById(relationId);
		if (issueRelation == null) {
			return toAjax(0);
		}
		int result = issueRelationService.deleteIssueRelationById(issueRelation);
		if (result > 0) {

			IssueRelation toRelation = issueRelationService.findRelationByFromIdAndToId(issueRelation.getIssueToId(),
					issueRelation.getIssueFromId());
			if (toRelation != null) {
				issueRelationService.deleteIssueRelationById(toRelation);
			}

		}
		return toAjax(result);
	}

	/**
	 * 打开关联问题模态框
	 */
	@GetMapping("/modal/{id}")
	public String relationModal(@PathVariable("id") Long issueId, ModelMap mmap) {
		mmap.put("issueId", issueId);
		return prefix + "/issue_relation_modal";
	}

}
